<template>
  <div class="detection">
    <div class="left">
      <!-- <div class="list">
          <div
            class="item"
            v-for="(item, index) in gatewayList"
            :key="item.id"
            :class="{ active: active === index }"
            @click="getChannel(item.gatewayCode, index)"
          >
            <div class="img"></div>
            <div class="msg">{{ item.gatewayName }}</div>
          </div>
        </div> -->
      <div class="ee"></div>

      <div class="tree_1">
        <el-tree
          ref="tree"
          :data="gatewayList"
          :props="defaultProps"
          @node-click="handleNodeClick"
          node-key="id"
          highlight-current
        >
          <span slot-scope="{ node, data }">
            <div style="display: flex">
              <span style="transform: rotate(45deg)" v-if="!data.children">
                <i class="el-icon-arrow-down el-tree-node__content down"></i>
              </span>
              <span :class="{ boldfont: data.grade == '1', top: !data.grade }">{{ node.label }}</span>
            </div>
          </span>
        </el-tree>
      </div>
    </div>
    <div class="center">
      <div class="centerTop">
        <div class="channelListContainer">
          <div class="channelListItem" v-for="item in channelList" :key="item.index">
            <div class="name T">通道 {{ item.channel }}</div>
            <div class="status T" :class="{ statusType: item.status === '1' }">
              {{ item.status === '0' ? '正常' : '异常' }}
            </div>
            <!-- <div class="isSilence T" :class="{ isSilenceType: item.isSilence === 'false' }">
                {{ item.isSilence === 'true' ? '有' : '无' }}
              </div> -->
            <div class="level T">{{ item.soundPressureLevel }} Db</div>
            <div class="img T">
              <img src="../../../assets/img/detection/play.png" alt="" @click="playAudio(item)" />
            </div>
          </div>
        </div>
      </div>
      <div class="centerBottom">
        <div class="data">{{ pressureValue }}</div>
        <!--        <button :class="{activeBtn : openVoice}" class="BTN open" @click="openOrCloseAudio(true)">播放</button>-->
        <!--        <button :class="{activeBtn : !openVoice}" class="BTN stop" @click="openOrCloseAudio(false)">停止</button>-->
        <div class="BTN aaa">实时音频状态</div>
        <div class="BTN bbb" @click="play">{{ openVoice ? '播放中' : '已暂停' }}</div>
      </div>
    </div>
    <div class="right">
      <el-select class="select" v-model="value" placeholder="请选择" @change="changeCharts(value)">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>

      <div class="channel">位置： {{ installLocation }}</div>
      <div class="chartContainer" v-show="lili"></div>
      <div class="yuanyuan">
        <DrawCpn :dataArray="dataArray" v-show="!lili"></DrawCpn>
      </div>
    </div>
  </div>
</template>
    
  
  <script>
import { getAllDevice } from '@/api/yuan'
import PCMPlayer from './pcm-player'
import * as echarts from 'echarts'
import DrawCpn from '@/views/system/index/componentDetection/DrawCpn'
import { axios } from '@/utils/request'

export default {
  components: { DrawCpn },

  data() {
    return {
      gatewayCode: '', //网关code
      defaultProps: {
        children: 'children',
        label: 'label',
        grade: 'grade',
      },
      active: -1, //网关选择
      gatewayList: [],
      channelList: [],
      channel: '1', //通道号
      installLocation: '/', //通道位置
      pressureValue: '', //声压值
      socket: null,
      audioContext: null,
      audioSource: null,
      player: null,
      openVoice: false, //是否播放音乐
      audioUrl: null, //音频源
      randomId: parseInt(Math.random() * 10000 + ''),
      //时间
      startValue: 0,
      temArr: [],
      tem: 0.2,
      options: [
        {
          value: '1',
          label: '时域图',
        },
        {
          value: '2',
          label: '频域图',
        },
        // {
        //   value: '3',
        //   label: '时频域图'
        // }
      ], //选择图表
      value: '1', //选择的图标值
      myChart: null,
      option: {},
      chartData: {
        xData: [],
        yData: [],
        data: [],
        label: '',
      },
      dataArray: [],
      lili: true,
    }
  },

  async mounted() {
    await this.getGatewayListData()
    this.init()
  },
  methods: {
    async getGatewayListData() {
      // const ID = id || window.localStorage.getItem('stationIdByYuan')
      // const {
      //   data: { gatewayList },
      // } = await getAllDevice(ID)
      // this.gatewayList = gatewayList

      // console.log(this.gatewayList)

      let { data } = await axios.get('/index/station/gatewayTree')

      this.gatewayList = data
    },
    init: function () {
      this.initChart()
      this.player = new PCMPlayer({
        encoding: '16bitInt',
        channels: 1,
        sampleRate: 16000,
        flushingTime: 1000,
      })
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        const url = window.CONST.VUE_APP_WS_URL + this.randomId + ''
        // 实例化socket
        this.socket = new WebSocket(url)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log('socket连接成功')
    },
    error: function () {
      const that = this
      console.log('连接错误,5秒后重新连接')
      // 5秒后重新连接
      setTimeout(function () {
        that.init()
      }, 5000)
    },
    getMessage: function (msg) {
      if (msg.data == 'OFFLINE') return this.$message.warning('设备离线')

      const data = JSON.parse(msg.data)
      const { data: dataS, cmd } = data

      console.log(data)

      if (cmd === 'REPLY_SELF_INSPECTION') {
        this.channelList = dataS
      }
      if (cmd === 'REPLY_START') {
        const { audio, xAxis, yAxis, type, colorData } = dataS

        const data = new Uint8Array(audio)

        console.log(data)
        // if (this.openVoice) {
        if (this.openVoice) {
          this.player.feed(data)
        }
        // } else {
        //   this.player.destroy()
        // }
        if (type === '1') {
          this.lili = true
          const text = '时域图'
          const color = '#555'
          this.updateChartsData(xAxis, yAxis, color, text)
        }
        if (type === '2') {
          this.lili = true
          const text = '频域图'
          const color = '#333'
          this.updateChartsDataTwo(xAxis, yAxis, color, text)
        }
        if (type === '3') {
          this.lili = false
          const text = '时频域图'
          const color = '#111'
        }
      }
    },
    send: function (params) {
      if (this.socket) {
        this.socket.send(params)
      }
    },
    close: function () {
      console.log('socket已经关闭')
    },
    //关闭socket连接
    closeSocket() {
      this.openVoice = false
      const data = {
        from: this.randomId, //发送者
        to: this.gatewayCode, //接收者
        cmd: 'STOP', //自检指令指令
      }
      this.send(JSON.stringify(data))
    },

    //根据网关切换通道列表

    handleNodeClick(node) {
      if (!node.grade) {
        this.gatewayCode = node.id

        this.openVoice = true
        this.closeSocket()
        this.gatewayCode = node.id
        const data = {
          from: this.randomId, //发送者
          to: node.id, //接收者
          cmd: 'SELF_INSPECTION', //自检指令指令
        }

        this.send(JSON.stringify(data))
      }
    },

    //播放声道图表
    async playAudio(item) {
      let { data } = await axios.post('/bizGatewayChannel/gatewayChannel', {
        gatewayCode: this.gatewayCode, //网关编号
        channel: item.channel, //通道
      })

      console.log(data)

      this.installLocation = data.installLocation

      this.openVoice = true
      this.pressureValue = item.soundPressureLevel || '0'
      this.channel = item.channel || '1'
      this.changeCharts('1')
      this.value = '1'
    },
    //切换图表
    changeCharts(chart) {
      this.closeSocket()
      const data = {
        from: this.randomId, //发送者
        to: this.gatewayCode, //接收者
        cmd: 'START', //自检指令指令
        data: {
          channel: this.channel,
          type: chart,
        },
      }
      this.send(JSON.stringify(data))
      this.openVoice = true
    },
    initChart() {
      const charts = document.querySelector('.chartContainer')

      if (charts) {
        this.myChart = echarts.init(charts, null, {
          renderer: 'webgl',
        })
      }
    },
    updateChartsData(xData, yData, color, text = '时频图') {
      console.log(xData)
      const that = this
      if (that.chartData.yData.length >= 48) {
        that.chartData.yData.splice(0, 1)
        that.chartData.xData.splice(0, 1)
      } else {
        that.chartData.yData.push(...yData)
        that.chartData.xData.push(...xData)
      }

      if (xData) {
        this.temArr = []
        this.tem = xData[1] - xData[0] || 0.2
        for (let i = 0; i < that.chartData.xData.length; i++) {
          const v = (this.tem * i + this.startValue).toFixed(2) - 0
          this.temArr.push(v)
        }
        this.startValue = this.temArr[this.temArr.length - 1] || 0.1
      }

      that.option = {
        animation: false,
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          name: '时间/s',
          type: 'category',
          data: this.temArr,
          axisLine: {
            lineStyle: {
              color: '#FFF',
            },
          },
        },

        yAxis: {
          name: '幅度',
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#FFF',
            },
          },
        },
        series: [
          {
            data: that.chartData.yData,
            type: 'line',
            itemStyle: {
              color: '#19ecff',
            },
          },
        ],
      }
      that.myChart.setOption(that.option)
    },
    updateChartsDataTwo(xData, yData, color, text = '时频图') {
      const that = this
      that.option = {
        animation: false,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        xAxis: {
          name: '频率/Hz',
          type: 'category',
          data: xData,
          axisLine: {
            lineStyle: {
              color: '#FFF',
            },
          },
        },
        yAxis: {
          name: '幅值/dB',
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#FFF',
            },
          },
        },
        series: [
          {
            data: yData,
            type: 'line',
            itemStyle: {
              color: '#19ecff',
            },
          },
        ],
      }
      that.myChart.setOption(that.option)
    },
    openOrCloseAudio(judgement) {
      this.openVoice = judgement
      if (judgement) {
      } else {
      }
    },
    play() {
      this.openVoice = !this.openVoice
    },
  },

  destroyed() {
    this.openOrCloseAudio(false)
    const data = {
      from: this.randomId, //发送者
      to: this.gatewayCode, //接收者
      cmd: 'STOP', //自检指令指令
    }
    this.send(JSON.stringify(data))
  },
}
</script>
  
  <style lang="less" scoped>
@import '../~@/assets/css/list.less';

.detection {
  //   width: 1592px;
  height: 916px;
  display: flex;
  justify-content: space-between;

  .left {
    width: 289px;
    height: 916px;
    box-sizing: border-box;
    overflow: hidden;

    background-image: url(~@/assets/img/menu_border.png);

    background-size: 100% 100%;

    color: #fff;

    padding: 0 10px;
    .ee {
      width: 100%;

      height: 50px;
    }
    .tree_1 {
      margin-top: 10px;
    }

    ::v-deep(.el-tree) {
      background: transparent;
      color: #fff;
      .boldfont {
        font-weight: 700;
      }

      .down {
        font-size: 20px;
      }

      .top {
        margin-top: 7px;
      }

      .el-tree-node.is-current > .el-tree-node__content {
        background-color: #1890ff !important;
        color: #ffffff;
      }

      .el-tree-node__content:hover {
        background: transparent !important;
        color: #1890ff;
      }
    }
  }

  .center {
    width: 417px;
    height: 916px;

    .centerTop {
      width: 417px;
      height: 495px;
      background: url('./img/Group2037.png') no-repeat center;
      background-size: 100% 100%;
      position: relative;

      .channelListContainer {
        position: absolute;
        width: 347px;
        height: 360px;
        top: 114px;
        left: 35px;
        box-sizing: border-box;
        overflow: auto;

        .channelListItem {
          background-color: #e6f0ff;

          display: flex;
          justify-content: flex-start;
          width: 347px;
          height: 34px;

          &:hover {
            background-color: #82b4ff;
            color: #fff;
          }

          .T {
            text-align: center;
            line-height: 32px;
            font-size: 14px;
          }

          .name {
            width: 82px;
          }

          .status {
            width: 52px;
            color: #0bce2f;
            margin-left: 25px;
          }

          .statusType {
            color: #ff0000;
          }

          .isSilence {
            width: 80px;
            color: #0bce2f;
          }

          .isSilenceType {
            color: #ff0000;
          }

          .level {
            width: 60px;
            margin-left: 30px;
          }

          .img {
            cursor: pointer;
            width: 72px;
            margin-left: 30px;

            img {
              width: 20px;
              height: 20px;
            }
          }
        }
      }
    }

    .centerBottom {
      margin-top: 20px;
      width: 417px;
      height: 401px;
      background: url('./img/Group2038.png') no-repeat center;
      background-size: 100% 100%;
      position: relative;

      .data {
        position: absolute;
        top: 115px;
        left: 228px;
        font-size: 32px;
        height: 36px;
        line-height: 36px;
        color: #0bce2f;
      }

      .BTN {
        cursor: pointer;
        position: absolute;
        width: 100px;
        height: 36px;
        border: none;
      }

      .aaa {
        top: 280px;
        right: 88px;
        font-size: 16px;
        font-weight: bold;
      }

      .bbb {
        top: 330px;
        right: 88px;
        background-color: #0469ff;
        color: #fff;
        text-align: center;
        font-size: 14px;
        line-height: 36px;
      }
    }
  }

  .right {
    width: 849px;
    height: 916px;
    background: url('./img/Group2060.png') no-repeat center;
    background-size: 100% 100%;
    position: relative;

    .select {
      position: absolute;
      top: 10px;
      left: 22px;
    }

    ::v-deep .el-scrollbar {
      background: #fff !important;
    }
    .channel {
      position: absolute;
      top: 20px;
      left: 265px;
      font-size: 16px;
      height: 18px;
      line-height: 18px;
      color: #fff;
    }

    .chartContainer {
      position: absolute;
      top: 60px;
      width: 849px;
      height: 500px;
      //border: 1px solid brown;
    }

    .yuanyuan {
      position: absolute;
      top: 80px;
      width: 849px;
      height: 500px;
    }
  }
}
</style>
  